// packageA/pages/partStock/partStock.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //配件库
    depot:{
      id:null,
      name:'配件库'
    },
    //配件分类
    category:{
      id:null,
      name:'配件分类'
    },
    factory:{
      id:null,
      name:'配件厂家'
    },
    //库存预警
    showWarning:false,
    warningNum:30,
    //预警id
    warningId:null,
    //配件分类列表
    categoryList:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //获取配件分类
    this.getPartsCategoryList(); 
    
    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      type:2,
      selectFields: ['id', 'name', 'cargoesId', 'num', 'depot', 'state', 'type', 'spec', 'inventoryWarning', 'category','code', 'appId', 'dataAuthority', 'unitName', 'factory'],
      sort: {
        _id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }
    
    //配件编码
    if(this.data.searchValue){
      dataObj.code='%' +this.data.searchValue+ '%';
    }

    //配件库
    if(this.data.depot.id){
      dataObj['depot.id']=this.data.depot.id;
    }

    //配件厂家
    if(this.data.factory.id){
      dataObj['factory.id']=this.data.factory.id;
    }
    
    let param = {
      isAuth: true,
      className: 'repertory',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        
        console.log('配件库存列表');
        console.log(result);
        
        result.forEach(item => {
          if(item.category) {
            let name = this.getCategoryName(item.category, 0, this.data.categoryList, '');
            name=name.substring(0, name.length - 3);
            item.categoryStr=name;
          }
        });  

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //配件库
    if(field=='depot'){
      this.setData({
        selectTitle: '配件库',
        showSelectSearch:true
      })
      this.getDepotList();
    }

    //配件分类
    if(field=='category'){
      this.setData({
        selectTitle: '配件分类',
        showSelectSearch:true
      })
      this.getCategoryList();
    }

    //配件厂家
    if(field=='factory'){
      this.setData({
        selectTitle: '配件厂家',
        showSelectSearch:true
      })
      this.getFactoryList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    }) 
    
    this.refreshListAndPage();
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //配件库
    if(selectField=='depot'){
      obj='depot';
    }

    //配件分类
    if(selectField=='category'){
      obj='category';
    }

    //配件厂家
    if(selectField=='factory'){
      obj='factory';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null;

    //配件库
    if(selectField=='depot'){
      id='depot.id';
      let name='depot.name';
      this.setData({
        [name]:'配件库'
      })
    }

    //配件分类
    if(selectField=='category'){
      id='category.id';
      let name='category.name';
      this.setData({
        [name]:'配件分类'
      })
    }

    //配件厂家
    if(selectField=='factory'){
      id='factory.id';
      let name='factory.name';
      this.setData({
        [name]:'配件厂家'
      })
    }

    if(id){
      this.setData({
        [id]:null
      })
    }    

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //配件库
    if(selectField=='depot'){
      this.getDepotList();
    }

    //配件分类
    if(selectField=='category'){
      this.getCategoryList();
    }

    //配件厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }
  },

  //查询配件库
  getDepotList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'partsDepots',
      data: {
        searchAll: true,  
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询配件分类？？？
  getCategoryList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'partsDepots',
      data: {
        searchAll: true,  
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询配件厂家
  getFactoryList(){
    this.setData({
      selectList: []
    })

    let param = {
      isAuth: true,
      className: 'supplierFactories',
      data: {
        searchAll: true,  
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //出库
  goToOut(e){
    let detail=e.currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/partStockOut/partStockOut?paramObj="+JSON.stringify(obj)
    })
  }, 

  //显示库存预警
  onShowWarning(e){
    let detail=e.currentTarget.dataset.detail;
    this.setData({
      showWarning: true,
      warningId: detail.id,
      warningNum: detail.inventoryWarning ? detail.inventoryWarning : 30
    })
  },

  //隐藏库存预警
  onCloseWarning(){
    this.setData({
      showWarning: false
    })
  },

  //预警数量
  onChangeWarning(e){
    this.setData({
      warningNum: e.detail
    })
  },

  //确认库存预警
  onConfirmWarning(){
    let param={
      className:'repertory',
      data:{
        id: this.data.warningId,
        inventoryWarning: this.data.warningNum
      }
    }

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('设置成功');

        this.onCloseWarning();
        
        setTimeout(() => {
          this.refreshListAndPage();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取配件分类
  getPartsCategoryList(){
    let data = {
      otherFields: ['describe']
    }

    CommonService.getPartsCategoryTree(data).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        this.setData({
          categoryList: res.data.data.result
        })
      }
    }).catch((error) => {
    })
  },

  //获取配件分类名称
  getCategoryName(ids, index, menu, name) {
    for (let i = 0; i < menu.length; i++) {
      if (menu[i].id === ids[index]) {
        name += menu[i].name + " / ";
        if (menu[i].children && index < ids.length) {
          index++;
          return this.getCategoryName(ids, index, menu[i].children, name);
        }
      }
    }
    return name;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})